package com.aster.service.manage.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aster.common.annotation.Log;
import com.aster.common.base.BaseController;
import com.aster.common.base.BaseDomain;
import com.aster.common.dto.UserToken;
import com.aster.common.exception.ServiceException;
import com.aster.common.utils.PageUtils;
import com.aster.common.utils.Query;
import com.aster.common.utils.R;
import com.aster.service.manage.dao.EscortEnterpriseInfoDao;
import com.aster.service.manage.dao.EscortUserInfoDao;
import com.aster.service.manage.domain.*;
import com.aster.service.manage.dto.DtoEscortEnterpriseInfo;
import com.aster.service.manage.dto.DtoEscortUserInfo;
import com.aster.service.manage.dto.DtoEscortUserLabelInfo;
import com.aster.service.manage.dto.DtoLabelInfo;
import com.aster.service.manage.dto.do2dto.EscortEnterpriseInfoConvert;
import com.aster.service.manage.dto.do2dto.EscortUserInfoConvert;
import com.aster.service.manage.dto.do2dto.EscortUserLabelInfoConvert;
import com.aster.service.manage.dto.do2dto.LabelInfoConvert;
import com.aster.service.manage.service.*;
import com.aster.service.manage.service.criteria.EscortEnterpriseInfoCriteria;
import com.aster.service.manage.service.criteria.EscortUserInfoCriteria;
import com.aster.service.manage.service.criteria.EscortUserLabelInfoCriteria;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <br>
 * <b>功能：</b>TbEscortUserInfoController<br>
 *   <br>
 */
@RestController
@RequestMapping("/escortUser")
public class EscortUserInfoController extends BaseController {
	
	private final static Logger log= Logger.getLogger(EscortUserInfoController.class);
	@Autowired(required=false) 
	private EscortUserInfoService tbEscortUserInfoService;
	@Autowired(required=false)
	private CommissionRatioInfoService commissionRatioInfoService;
	@Autowired
	private EscortEnterpriseInfoDao escortEnterpriseInfoDao;
	@Autowired
	private EscortUserLabelInfoService escortUserLabelInfoService;

	@Log("陪护员列表")
	@GetMapping
	public R listByPage(@RequestParam Map<String, Object> params, HttpServletRequest headers){
		try {
			UserToken userToken = getUserToken(headers);
			Query query = new Query(params);
			EscortUserInfoCriteria criteria = new EscortUserInfoCriteria();
			criteria.setPageSize(query.getLimit());
			criteria.setCurrentPage(query.getPage());
			Map<String,Object> likeMap = new HashMap<>();
			likeMap.put("name",query.get("name"));
			criteria.setConditionLike(likeMap);
			Map<String,Object> map = new HashMap<>();
			map.put("deleted",1);
			map.put("enterpriseId",userToken.getEnterpriseId());
			criteria.setCondition(map);
			criteria.setOrderByClause("id");
			PageUtils pageUtils = tbEscortUserInfoService.getEscortUserInfoForPage(criteria);
			return R.ok().put("page",pageUtils);
		} catch (ServiceException e) {
			e.printStackTrace();
			return R.error(e.getMessage());
		}
	}

	@Log("根据id获取用户信息")
	@RequestMapping("/getById")
	public R getById(@RequestParam Map<String, Object> params){
		try{
			String idStr = (String) params.get("id");
			int id = Integer.parseInt(idStr);
			TbEscortUserInfo info = tbEscortUserInfoService.queryById(id);
			DtoEscortUserInfo dtoEscortUserInfo = EscortUserInfoConvert.MAPPER.do2dto(info);
			// 根据ID获取陪护金,还有数据状态
			TbCommissionRatioInfo commissionRatioInfo = new TbCommissionRatioInfo();
			commissionRatioInfo.setState(0);
			commissionRatioInfo.setEscortUserId(id);
			commissionRatioInfo = commissionRatioInfoService.queryByEscortUserIdAndState(commissionRatioInfo);
			if (commissionRatioInfo != null){
				dtoEscortUserInfo.setCommissionRatio(commissionRatioInfo.getCommissionRatio());
			}

			// 根据企业ID取出企业名称
			TbEscortEnterpriseInfo escortEnterpriseInfo = new TbEscortEnterpriseInfo();
			escortEnterpriseInfo.setId(dtoEscortUserInfo.getEnterpriseId());
			escortEnterpriseInfo = escortEnterpriseInfoDao.selectByOne(escortEnterpriseInfo);
			if (escortEnterpriseInfo != null){
				dtoEscortUserInfo.setEnterpriseName(escortEnterpriseInfo.getName());
			}

			// 根据陪护员ID、企业id取出陪护员所有的标签
			EscortUserLabelInfoCriteria escortUserLabelInfoCriteria = new EscortUserLabelInfoCriteria();
			Map<String,Object> map = new HashMap<>();
			map.put("deleted",1);
			map.put("state",1);
			map.put("escortUserId",id);
			map.put("enterpriseId",dtoEscortUserInfo.getEnterpriseId());
			escortUserLabelInfoCriteria.setCondition(map);
			escortUserLabelInfoCriteria.setOrderByClause("id");
			escortUserLabelInfoCriteria.setCurrentPage(1);
			Integer totalCount = escortUserLabelInfoService.queryByCount(escortUserLabelInfoCriteria);
			escortUserLabelInfoCriteria.setPageSize(totalCount);
			List<TbEscortUserLabelInfo> list = escortUserLabelInfoService.queryByList(escortUserLabelInfoCriteria);
			List<Integer> labelInt = new ArrayList<>();
			if (list != null){
				for (TbEscortUserLabelInfo tbEscortUserLabelInfo: list) {
					labelInt.add(tbEscortUserLabelInfo.getLabelId());
				}
			}
			dtoEscortUserInfo.setLabel(labelInt);
			return R.ok().put("info",dtoEscortUserInfo);
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}catch (NumberFormatException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("添加陪护员信息")
	@PostMapping("/add")
	public R add(@RequestBody DtoEscortUserInfo dtoEscortUserInfo, HttpServletRequest headers){
		try {
			UserToken userToken = getUserToken(headers);

			if(userToken == null){
				return R.error401();
			}
			TbEscortUserInfo tbEscortUserInfo = EscortUserInfoConvert.MAPPER.addData(dtoEscortUserInfo);
			tbEscortUserInfoService.addEscortUserInfo(tbEscortUserInfo,userToken);

			Integer commissionRetio = dtoEscortUserInfo.getCommissionRatio();
			//取出所存储员工的id
			TbEscortUserInfo escortUserInfo =tbEscortUserInfoService.selectByOne(tbEscortUserInfo);
			if (commissionRetio != null){
				// 存储佣金
				TbCommissionRatioInfo tbCommissionRatioInfo = new TbCommissionRatioInfo();
				tbCommissionRatioInfo.setEscortUserId(escortUserInfo.getId());
				tbCommissionRatioInfo.setCommissionRatio(commissionRetio);
				commissionRatioInfoService.addCommissionRatioInfo(tbCommissionRatioInfo,userToken);
			}
			List<Integer> labelList = dtoEscortUserInfo.getLabel();
			// 存储陪护员标签
			if (labelList != null){
				for (Integer labelId:labelList) {
					TbEscortUserLabelInfo escortUserLabelInfo = new TbEscortUserLabelInfo();
					escortUserLabelInfo.setEscortUserId(escortUserInfo.getId());
					escortUserLabelInfo.setLabelId(labelId);
					escortUserLabelInfoService.addEscortUserLabelInfo(escortUserLabelInfo,userToken);
				}
			}
			return R.ok();
		}
		catch (ServiceException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("编辑陪护员信息")
	@PostMapping("/edit")
	public R editState(@RequestBody DtoEscortUserInfo dtoEscortUserInfo , HttpServletRequest headers){
		try {
			UserToken userToken = getUserToken(headers);
			TbEscortUserInfo tbEscortUserInfo = EscortUserInfoConvert.MAPPER.dto2do(dtoEscortUserInfo);
			tbEscortUserInfoService.editEscortUserInfo(tbEscortUserInfo,userToken);

			// 获取出当前陪护员的佣金比例
			TbCommissionRatioInfo commissionRatioInfo = new TbCommissionRatioInfo();
			commissionRatioInfo.setEscortUserId(tbEscortUserInfo.getId());
			commissionRatioInfo.setState(0);
			commissionRatioInfo = commissionRatioInfoService.queryByEscortUserIdAndState(commissionRatioInfo);
			if (commissionRatioInfo != null){
				// 如果编辑的佣金比例值跟佣金表表最新的值不一致，则更新佣金表
				if (commissionRatioInfo.getCommissionRatio() != dtoEscortUserInfo.getCommissionRatio()){
					commissionRatioInfo.setUpdateTime(new Date());
					commissionRatioInfo.setUpdateUserId(Integer.parseInt(userToken.getUserId()));
					commissionRatioInfo.setState(1);
					commissionRatioInfoService.update(commissionRatioInfo);
					// 新增一个佣金拉链
					TbCommissionRatioInfo lastInfo = new TbCommissionRatioInfo();
					lastInfo.setEscortUserId(dtoEscortUserInfo.getId());
					lastInfo.setCommissionRatio(dtoEscortUserInfo.getCommissionRatio());
					commissionRatioInfoService.addCommissionRatioInfo(lastInfo,userToken);
				}
			}else {
				//如果没有过佣金值，则 新增一个佣金拉链
				TbCommissionRatioInfo lastInfo = new TbCommissionRatioInfo();
				lastInfo.setEscortUserId(dtoEscortUserInfo.getId());
				lastInfo.setCommissionRatio(dtoEscortUserInfo.getCommissionRatio());
				commissionRatioInfoService.addCommissionRatioInfo(lastInfo,userToken);
			}

			// 先删除掉陪护员所有标签
			TbEscortUserLabelInfo tbEscortUserLabelInfo = new TbEscortUserLabelInfo();
			tbEscortUserLabelInfo.setEscortUserId(dtoEscortUserInfo.getId());
			tbEscortUserLabelInfo.setEnterpriseId(dtoEscortUserInfo.getEnterpriseId());
			escortUserLabelInfoService.deleteByEscortUserIdAndEnterpriseId(tbEscortUserLabelInfo);
			// 然后给陪护员新增标签
			List<Integer> labelInt = dtoEscortUserInfo.getLabel();
			if (labelInt != null){
				for (Integer label:labelInt) {
					TbEscortUserLabelInfo escortUserLabelInfo = new TbEscortUserLabelInfo();
					escortUserLabelInfo.setLabelId(label);
					escortUserLabelInfo.setEscortUserId(dtoEscortUserInfo.getId());
					escortUserLabelInfo.setEnterpriseId(dtoEscortUserInfo.getEnterpriseId());
					escortUserLabelInfoService.addEscortUserLabelInfo(escortUserLabelInfo,userToken);
				}
			}
			return R.ok();
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("删除陪护员信息")
	@PostMapping("/delete")
	public R delete(@RequestBody DtoEscortUserInfo dtoEscortUserInfo ,HttpServletRequest headers){
		try{
			if(dtoEscortUserInfo == null){
				return R.error(10001,"传入参数为空");
			}
			if(dtoEscortUserInfo.getId() == 0){
				return R.error(10001,"传入参数为空");
			}
			UserToken userToken = getUserToken(headers);
			if(userToken == null){
				return R.error401();
			}
			dtoEscortUserInfo.setDeleted(BaseDomain.DELETED.NO.key);
			TbEscortUserInfo tbEscortUserInfo = EscortUserInfoConvert.MAPPER.updateDeleted(dtoEscortUserInfo);
			tbEscortUserInfoService.editEscortUserInfo(tbEscortUserInfo,userToken);
			return R.ok();
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("修改陪护员数据状态")
	@PostMapping("/changeState")
	public R changeState(@RequestBody DtoEscortUserInfo dtoEscortUserInfo,HttpServletRequest headers){
		try {
			if(dtoEscortUserInfo == null){
				return R.error(10001,"传入参数为空");
			}
			if(dtoEscortUserInfo.getId() == 0){
				return R.error(10001,"传入参数为空");
			}
			UserToken userToken = getUserToken(headers);
			if(userToken == null){
				return R.error401();
			}
			TbEscortUserInfo tbEscortUserInfo = EscortUserInfoConvert.MAPPER.updateState(dtoEscortUserInfo);
			tbEscortUserInfoService.editEscortUserInfo(tbEscortUserInfo,userToken);
			return R.ok();
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}
}
